<?php
/*
 * description：
 * author：wh
 * email：
 * createTime：{2022/03/08} {14:17} 
 */

namespace wanghua\general_utility_tools_php\exception;


use think\exception\Handle;
use think\Request;
use wanghua\general_utility_tools_php\SundryConfig;
use wanghua\general_utility_tools_php\tool\EmailTool;
use wanghua\general_utility_tools_php\tool\Tools;

class SystemException extends Handle
{
    public function render(\Exception $e)
    {
        // 参数验证错误
        //if ($e instanceof ValidateException) {
        //    return json($e->getError(), 422);
        //}

        // 请求异常
        //if ($e instanceof HttpException && request()->isAjax()) {
        //    return response($e->getMessage(), $e->getStatusCode());
        //}

        Tools::log_to_write_txt([
            'error'=>'系统错误.'.$e->getMessage(),
            'input'=>Request::instance()->input(),
            'error_info'=>$e->getTraceAsString()
        ]);

        $title = '新的【系统异常】，请立即处理';
        //邮件通知管理员
        $mail_content = '<p>error：'.$e->getMessage().'</p>';
        $mail_content .= '<p>url：'.request()->url(true).'</p>';
        $mail_content .= '<p>ip：'.request()->ip().'</p>';
        $mail_content .= '<p>详情请登录宝塔查看日志</p>';

        $emails = SundryConfig::val('admin_error_log_email');
        if(config('sys_env') == 'PROD'){//线上环境才发错误邮件
            EmailTool::email_to_person($title,$mail_content,$emails);
        }

        if(request()->LogObj){
            request()->LogObj->flush();
        }
        if(request()->ServeLogObj){
            request()->ServeLogObj->flush();
        }

        //可以在此交由系统处理
        return parent::render($e);
    }
}